package com.hit.sys.modular.auth.context;

import cn.hutool.core.util.ObjectUtil;
import com.hit.core.context.login.LoginContext;
import com.hit.core.exception.AuthException;
import com.hit.core.exception.enums.AuthExceptionEnum;
import com.hit.core.pojo.login.SysLoginUser;
import com.hit.sys.modular.auth.service.AuthService;
import com.hit.sys.modular.user.service.SysUserService;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class LoginContextImpl implements LoginContext {

    @Resource
    private AuthService authService;

    @Resource
    private SysUserService sysUserService;

    private LoginContextImpl() {}

    @Override
    public SysLoginUser getSysLoginUser() {
        Authentication authentication = authService.getAuthentication();
        if (ObjectUtil.isEmpty(authentication) || authentication.getPrincipal() instanceof String) {
            throw new AuthException(AuthExceptionEnum.NO_LOGIN_USER);
        } else {
            return (SysLoginUser) authentication.getPrincipal();
        }
    }

    @Override
    public SysLoginUser getSysLoginUserWithoutException() {
        Authentication authentication = authService.getAuthentication();
        if (ObjectUtil.isEmpty(authentication) || authentication.getPrincipal() instanceof String) {
            return null;
        } else {
            return (SysLoginUser) authentication.getPrincipal();
        }
    }

    @Override
    public Long getSysLoginUserId() {
        return this.getSysLoginUser().getId();
    }

    @Override
    public boolean hasLogin() {
        Authentication authentication = authService.getAuthentication();
        if (ObjectUtil.isEmpty(authentication) || authentication.getPrincipal() instanceof String) {
            return false;
        } else {
            return !(authentication instanceof AnonymousAuthenticationToken);
        }
    }
}
